import { defineStore } from 'pinia';
import { 
  getProducts, 
  getProductById, 
  createOrder, 
  getMyBuyOrders, 
  getOrderById, 
  payOrder, 
  receiveOrder, 
  cancelOrder,
  fetchAllProducts,
  getComplaints,
  createComplaint,
  getComplaintDetail,
  followUpComplaint,
  closeComplaint,
  getTransactions
} from '../../api/buyer';
import { ElMessage } from 'element-plus';

export const useBuyerStore = defineStore('buyer', {
  state: () => ({
    products: [],
    productDetail: null,
    orders: [],
    currentOrder: null,
    farmers: [],
    currentFarmer: null,
    complaints: [],
    currentComplaint: null,
    transactions: [],
    loading: false
  }),

  getters: {
    pendingOrders: (state) => state.orders.filter(order => order.status === 'pending'),
    processingOrders: (state) => state.orders.filter(order => order.status === 'processing'),
    completedOrders: (state) => state.orders.filter(order => order.status === 'completed'),
    cancelledOrders: (state) => state.orders.filter(order => order.status === 'cancelled'),
    totalOrderValue: (state) => state.orders.reduce((sum, order) => sum + order.totalAmount, 0),
    pendingComplaints: (state) => state.complaints.filter(complaint => complaint.status === 'pending')
  },

  actions: {
    // 获取产品列表
    async fetchProducts(params) {
      try {
        const response = await getProducts(params);
        if (!response || !response.data || !response.data.records) {
          return [];
        }
        
        // 转换格式
        const products = response.data.records.map(product => ({
          id: product.id,
          name: product.name,
          farmerId: product.farmerId,
          farmerName: product.farmerName,
          category: product.type,
          price: product.price,
          unit: product.unit,
          stock: product.stock,
          image: product.image,
          description: product.description,
          status: product.status === 1 ? 'selling' : 'draft'
        }));
        
        this.products = products;
        return products;
      } catch (error) {
        console.error('获取产品列表失败', error);
        return [];
      }
    },
    
    // 获取产品详情
    async getProductDetail(id) {
      try {
        const response = await getProductById(id);
        if (!response || !response.data) {
          return null;
        }
        
        const product = response.data;
        return {
          id: product.id,
          name: product.name,
          farmerId: product.farmerId,
          farmerName: product.farmerName,
          category: product.type,
          price: product.price,
          unit: product.unit,
          stock: product.stock,
          image: product.image,
          description: product.description,
          status: product.status === 1 ? 'selling' : 'draft'
        };
      } catch (error) {
        console.error('获取产品详情失败', error);
        return null;
      }
    },
    
    /**
     * 获取我的订单列表
     */
    async fetchOrders() {
      try {
        const response = await getMyBuyOrders();
        if (response.success) {
          // 处理后端返回的数据，转换为前端需要的格式
          const orderData = response.data.map(order => {
            // 将状态转换为前端格式
            const status = this.mapOrderStatus(order.status);
            const statusText = this.getStatusText(status);
            
            return {
              id: order.id,
              orderNumber: order.orderNo,
              buyerName: order.buyerName,
              buyerPhone: order.contactPhone,
              farmerId: order.sellerId,
              farmerName: order.sellerName,
              farmerPhone: order.sellerPhone,
              productId: order.productId,
              productName: order.productName,
              productImage: order.productImage,
              price: order.price,
              quantity: order.quantity,
              unit: order.unit || '件',
              totalAmount: order.totalAmount,
              total: order.totalAmount,
              address: order.address,
              // 转换订单状态
              status: status,
              statusText: statusText,
              note: order.remark,
              orderDate: order.orderTime,
              createdAt: order.orderTime,
              paymentMethod: 'online', // 默认在线支付
              deliveryMethod: 'express', // 默认快递
              statusHistory: this.generateStatusHistory(order)
            };
          });
          
          // 保存到状态中
          this.orders = orderData;
          console.log('订单数据保存到store中，共', orderData.length, '条记录');
          
          return orderData;
        }
        ElMessage.error(response.message || '获取订单失败');
        return [];
      } catch (error) {
        console.error('获取订单列表失败', error);
        ElMessage.error('获取订单列表失败');
        return [];
      }
    },
    
    /**
     * 订单状态映射
     */
    mapOrderStatus(status) {
      // 根据后端返回的数字状态映射为前端状态字符串
      const statusMap = {
        0: 'pending',  // 待付款
        1: 'paid',     // 已付款，待发货
        2: 'shipped',  // 已发货
        3: 'completed', // 已完成
        4: 'cancelled', // 已取消
        5: 'refunding', // 退款中
        6: 'refunded'   // 已退款
      };
      
      return statusMap[status] || 'pending';
    },
    
    /**
     * 生成订单状态历史
     */
    generateStatusHistory(order) {
      const history = [];
      
      // 创建订单
      history.push({
        status: 'pending',
        time: order.createTime,
        remark: '订单创建成功'
      });
      
      // 支付成功
      if (order.payTime) {
        history.push({
          status: 'paid',
          time: order.payTime,
          remark: '订单支付成功'
        });
      }
      
      // 已发货
      if (order.shipTime) {
        history.push({
          status: 'shipped',
          time: order.shipTime,
          remark: '商家已发货'
        });
      }
      
      // 已完成
      if (order.completeTime) {
        history.push({
          status: 'completed',
          time: order.completeTime,
          remark: '订单已完成'
        });
      }
      
      // 已取消（这里没有取消时间字段，需要根据实际情况添加）
      if (order.status === 4) {
        history.push({
          status: 'cancelled',
          time: order.updateTime,
          remark: '订单已取消'
        });
      }
      
      // 退款相关（这里没有退款时间字段，需要根据实际情况添加）
      if (order.status === 5 || order.status === 6) {
        history.push({
          status: order.status === 5 ? 'refunding' : 'refunded',
          time: order.updateTime,
          remark: order.status === 5 ? '退款申请中' : '退款已完成'
        });
      }
      
      return history;
    },
    
    // 创建订单
    async createOrder(orderData) {
      try {
        console.log('BuyerStore中提交订单数据:', orderData);
        
        // 校验订单数据的完整性
        if (!orderData.sellerId) {
          console.error('订单缺少必要的sellerId字段');
          ElMessage.error('订单数据不完整，请重新提交');
          throw new Error('订单缺少必要的sellerId字段');
        }
        
        const response = await createOrder(orderData);
        console.log('创建订单响应:', response);
        
        if (!response.success) {
          ElMessage.error(response.message || '创建订单失败');
          throw new Error(response.message || '创建订单失败');
        }
        
        return response.data;
      } catch (error) {
        console.error('创建订单失败', error);
        ElMessage.error('创建订单失败: ' + (error.message || '未知错误'));
        throw error;
      }
    },
    
    // 支付订单
    async payOrder(orderId) {
      try {
        const response = await payOrder(orderId);
        return response;
      } catch (error) {
        console.error('支付订单失败', error);
        throw error;
      }
    },
    
    // 确认收货
    async receiveOrder(orderId) {
      try {
        const response = await receiveOrder(orderId);
        return response;
      } catch (error) {
        console.error('确认收货失败', error);
        throw error;
      }
    },
    
    // 取消订单
    async cancelOrder(orderId) {
      console.log('准备取消订单，ID:', orderId);
      
      try {
        // 如果是从列表直接调用，可能需要重新获取最新订单列表
        if (this.orders.length === 0 || !this.orders.some(o => o.id == orderId)) {
          console.log('订单列表为空或未找到订单，尝试重新获取订单列表');
          await this.fetchOrders();
        }
        
        // 重新检查订单是否存在
        const order = this.orders.find(o => o.id == orderId || o.id == String(orderId));
        
        if (!order) {
          console.error('重新获取后仍找不到订单，ID:', orderId);
          // 直接调用API尝试取消，不进行本地验证
          console.log('尝试直接调用取消订单API');
          const response = await cancelOrder(orderId);
          console.log('取消订单API返回结果:', response);
          
          // 刷新订单列表
          await this.fetchOrders();
          return response;
        }
        
        // 检查订单状态是否可以取消 (pending或paid状态可以取消)
        if (order.status !== 'pending' && order.status !== 'paid') {
          console.error('订单状态不允许取消，当前状态:', order.status);
          throw new Error(`状态为"${this.mapOrderStatus(order.status)}"的订单无法取消`);
        }
        
        const response = await cancelOrder(orderId);
        console.log('取消订单成功，API响应:', response);
        
        // 更新本地订单状态
        if (response) {
          const index = this.orders.findIndex(o => o.id == orderId);
          if (index !== -1) {
            this.orders[index].status = 'cancelled';
            this.orders[index].statusText = this.mapOrderStatus('cancelled');
          }
        }
        
        return response;
      } catch (error) {
        console.error('取消订单失败', error);
        
        // 如果是后端拒绝取消已支付订单，给出更明确的错误信息
        if (error.message && error.message.includes('取消订单失败')) {
          throw new Error('已支付订单需要后端支持取消功能，请联系管理员修改后端代码');
        } else {
          throw new Error('取消订单失败: ' + (error.message || '未知错误'));
        }
      }
    },
    
    // 获取农户列表
    async fetchFarmers() {
      this.loading = true;
      try {
        // TODO: 实现API调用
        // Mock数据
        return [
          {
            id: 'farmer1',
            name: '李农夫',
            phone: '13866668888',
            address: '河南省郑州市中牟县',
            products: ['有机大米', '新鲜蔬菜'],
            rating: 4.8
          },
          {
            id: 'farmer2',
            name: '张种植',
            phone: '13955557777',
            address: '山东省济南市章丘区',
            products: ['新鲜胡萝卜', '油菜'],
            rating: 4.5
          },
          {
            id: 'farmer3',
            name: '王果园',
            phone: '13744446666',
            address: '陕西省西安市临潼区',
            products: ['红富士苹果', '梨'],
            rating: 4.9
          }
        ];
      } catch (error) {
        console.error('获取农户列表失败', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 获取投诉列表
    async fetchComplaints() {
      try {
        this.loading = true;
        console.log('Buyer Store: 开始获取投诉列表');
        const response = await getComplaints();
        console.log('Buyer Store: 投诉API响应:', response);
        
        if (response.success) {
          this.complaints = response.data;
          return this.complaints;
        } else {
          console.error('Buyer Store: 获取投诉列表失败:', response.message);
          throw new Error(response.message || '获取投诉失败');
        }
      } catch (error) {
        console.error('Buyer Store: 获取投诉列表出错:', error);
        this.complaints = [];
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 创建投诉
    async createComplaint(complaintData) {
      try {
        this.loading = true;
        const response = await createComplaint(complaintData);
        if (response.success) {
          ElMessage.success('投诉已提交');
          // 刷新投诉列表
          await this.fetchComplaints();
          return response.data;
        }
        ElMessage.error(response.message || '提交投诉失败');
        return null;
      } catch (error) {
        console.error('提交投诉失败', error);
        ElMessage.error('提交投诉失败: ' + (error.message || '未知错误'));
        return null;
      } finally {
        this.loading = false;
      }
    },
    
    // 获取投诉详情
    async getComplaintDetail(id) {
      try {
        this.loading = true;
        const response = await getComplaintDetail(id);
        if (response.success) {
          this.currentComplaint = response.data;
          return this.currentComplaint;
        }
        ElMessage.error(response.message || '获取投诉详情失败');
        return null;
      } catch (error) {
        console.error('获取投诉详情失败', error);
        ElMessage.error('获取投诉详情失败: ' + (error.message || '未知错误'));
        return null;
      } finally {
        this.loading = false;
      }
    },
    
    // 跟进投诉
    async followUpComplaint(id, content) {
      try {
        this.loading = true;
        const response = await followUpComplaint(id, content);
        if (response.success) {
          ElMessage.success('跟进内容已提交');
          // 刷新投诉列表
          await this.fetchComplaints();
          return true;
        }
        ElMessage.error(response.message || '提交跟进失败');
        return false;
      } catch (error) {
        console.error('提交跟进失败', error);
        ElMessage.error('提交跟进失败: ' + (error.message || '未知错误'));
        return false;
      } finally {
        this.loading = false;
      }
    },
    
    // 关闭投诉
    async closeComplaint(id) {
      try {
        this.loading = true;
        const response = await closeComplaint(id);
        if (response.success) {
          ElMessage.success('投诉已关闭');
          // 刷新投诉列表
          await this.fetchComplaints();
          return true;
        }
        ElMessage.error(response.message || '关闭投诉失败');
        return false;
      } catch (error) {
        console.error('关闭投诉失败', error);
        ElMessage.error('关闭投诉失败: ' + (error.message || '未知错误'));
        return false;
      } finally {
        this.loading = false;
      }
    },
    
    // 设置当前订单
    setCurrentOrder(order) {
      this.currentOrder = order;
    },
    
    // 设置当前农户
    setCurrentFarmer(farmer) {
      this.currentFarmer = farmer;
    },

    /**
     * 获取所有市场产品
     */
    async fetchAllProducts() {
      try {
        console.log('Store: 开始获取所有市场产品');
        const response = await fetchAllProducts();
        console.log('Store: 获取产品响应', response);
        
        if (response.success) {
          // 确保每个产品都有stock字段
          const products = response.data.map(product => {
            // 如果没有stock字段，设置为0
            if (product.stock === undefined || product.stock === null) {
              console.warn(`产品ID:${product.id} 没有库存字段，设置为默认值0`);
              product.stock = 0;
            }
            return product;
          });
          
          // 将获取的产品保存到store中
          this.products = products;
          
          return products;
        }
        
        ElMessage.error(response.message || '获取产品失败');
        return [];
      } catch (error) {
        console.error('获取产品列表失败', error);
        ElMessage.error('获取产品列表失败');
        return [];
      }
    },

    // 获取状态文本
    getStatusText(status) {
      const texts = {
        'pending': '待支付',
        'paid': '待发货',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消'
      };
      return texts[status] || '未知状态';
    },

    /**
     * 获取交易记录
     */
    async fetchTransactions(params = {}) {
      try {
        console.log('Store: 开始获取交易记录, 参数:', params);
        const response = await getTransactions(params);
        console.log('Store: 获取交易记录原始响应', response);
        
        if (response.success) {
          // 确保返回的数据是数组
          if (Array.isArray(response.data)) {
            this.transactions = response.data;
            console.log('Store: 交易记录获取成功，数量:', this.transactions.length);
            if (this.transactions.length > 0) {
              console.log('Store: 第一条交易记录示例:', this.transactions[0]);
            }
          } else {
            console.warn('Store: 交易记录数据不是数组格式:', response.data);
            this.transactions = [];
          }
          return this.transactions;
        } else {
          console.error('Store: 交易记录获取失败，API返回非成功状态:', response.message);
          ElMessage.error(response.message || '获取交易记录失败');
          return [];
        }
      } catch (error) {
        console.error('Store: 获取交易记录发生异常:', error);
        if (error.response) {
          console.error('Store: 错误响应:', error.response.data, '状态码:', error.response.status);
        }
        ElMessage.error('获取交易记录失败: ' + (error.message || '未知错误'));
        return [];
      }
    }
  }
}); 